package org.algorithm.熊猫.链表;

import org.algorithm.biubiu.wheel_1.common.ListNode;
import org.junit.Test;

/**
 * @Date 2022/2/26
 * @Link {https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii}
 */
public class 删除排序链表中的重复元素II {


    @Test
    public void test() {

        ListNode listNode = deleteDuplicates(ListNode.build(1, 2, 2));
        System.out.println("listNode = " + ListNode.print(listNode));


    }


    public ListNode deleteDuplicates(ListNode head) {
        ListNode dyNode = new ListNode();
        ListNode pre = dyNode;
        ListNode curtNode = head;

        while (curtNode != null) {
            int val = curtNode.val;
            ListNode next = curtNode.next;
            boolean flag = false;
            while (next != null && val == next.val) {
                next = next.next;
                flag = true;
            }

            //flag一次未进入，说明无重复 开始衔接返回值
            if (!flag) {
                ListNode end = new ListNode();
                end.val = curtNode.val;
                pre.next = end;
                pre = end;
            }
            curtNode.next = next;
            curtNode = next;
        }
        return dyNode.next;
    }
}
